package com.lch.thread.blocking;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author: liuchenhui
 * @create: 2019-06-02 13:39
 **/
public class UserServiceWithBlocking {

    static ArrayBlockingQueue<User> users = new ArrayBlockingQueue<User>(100);

    private final ExecutorService executorService = Executors.newFixedThreadPool(1);

    public UserServiceWithBlocking() {
        sendMsg();
    }

    public void register(String name, String phone) {
        User user = new User();
        user.setName(name);
        user.setPhone(phone);
        add(user);
        users.add(user);
    }

    public void add(User user) {
        try {
            Thread.sleep(100L);
            System.out.println("add:" + user);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void sendMsg() {
        executorService.execute(() -> {
            try {
                while (true) {
                    final User user = users.take();
                    System.out.println("senMsg:" + user);
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });
    }

    public static void main(String[] args) {
        UserServiceWithBlocking userServiceWithBlocking = new UserServiceWithBlocking();
        for (int i = 0; i < 100; i++) {
            userServiceWithBlocking.register("刘" + i, "123" + i);
        }
    }
}
